package com.gl.portal.system.repository;

import java.util.List;

import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;

import com.gl.portal.system.entity.SysMenu;

public interface SysMenuRepository extends JpaRepository<SysMenu, Long>, JpaSpecificationExecutor<SysMenu> {

	public interface UserMenuPermsVo {
		String getPerms();
	}

	/**
	 * 根据用户ID查询菜单权限
	 *
	 * @param userId
	 * @return
	 */
	@Query(value = "SELECT DISTINCT m.perms \n" + //
				   "FROM sys_menu m \n" + //
				   "    LEFT JOIN sys_role_menu rm ON m.id = rm.menu_id \n" + //
				   "    LEFT JOIN sys_user_role ur ON rm.role_id = ur.role_id \n" + //
				   "    LEFT JOIN sys_role r ON r.id = ur.role_id \n" + //
				   "WHERE m.`status` = 1 AND r.`status` = 1 AND ur.user_id = ?1", nativeQuery = true)
	List<UserMenuPermsVo> findMenuPermsByUserId(Long userId);

	/**
	 * 按菜单类型和状态查询菜单列表
	 *
	 * @param menuTypeList
	 * @param status
	 * @param sort
	 * @return
	 */
	List<SysMenu> findByMenuTypeInAndStatus(List<Integer> menuTypeList, Integer status, Sort sort);

	/**
	 * 查询用户菜单列表
	 *
	 * @param userId
	 * @return
	 */
	@Query(value = "SELECT DISTINCT m.id, m.parent_id, m.menu_name, m.path, m.component, m.visible, m.`status`, IFNULL(m.perms,'') AS perms, m.menu_type, m.icon, m.sort_num, m.create_time, m.creator, m.updator, m.update_time, u.create_user_id,u.is_deleted,u.update_user_id \n" + //
			       "FROM sys_menu m \n" + //
			       "    LEFT JOIN sys_role_menu rm ON m.id = rm.menu_id \n" + //
			       "    LEFT JOIN sys_user_role ur ON rm.role_id = ur.role_id \n" + //
			       "    LEFT JOIN sys_role ro ON ur.role_id = ro.id \n" + //
			       "    LEFT JOIN sys_user u ON ur.user_id = u.id \n" + //
			       "WHERE u.id = ?1 AND m.menu_type IN (1, 2) AND m.`status` = 1  AND ro.`status` = 1 \n" + //
			       "ORDER BY m.parent_id, m.sort_num", nativeQuery = true)
	List<SysMenu> selectMenuTreeByUserId(Long userId);

	public interface SelectedMenuIdVo {
		Long getId();
	}

	/**
	 * 根据角色ID查询菜单树信息
	 *
	 * @param roleId
	 * @return
	 */
	@Query(value = "SELECT m.id \n" + //
			       "FROM sys_menu m \n" + //
			       "    LEFT JOIN sys_role_menu rm ON m.id = rm.menu_id \n" + //
			       "WHERE rm.role_id = ?1 \n" + //
			       "    AND m.id NOT IN (SELECT m.parent_id FROM sys_menu m INNER JOIN sys_role_menu rm ON m.id = rm.menu_id AND rm.role_id = ?1) \n" + //
			       "ORDER BY m.parent_id, m.sort_num", nativeQuery = true)
	List<SelectedMenuIdVo> selectMenuListByRoleId(Long roleId);

	/**
	 * 是否存在菜单子节点
	 *
	 * @param parentId
	 * @return
	 */
	int countByParentId(Long parentId);

	SysMenu findByMenuNameAndParentId(String menuName, Long parentId);

}
